package com.yf.exam.modules.trainingarchives.studentinfo.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.yf.exam.common.entity.Result;
import com.yf.exam.core.api.ApiRest;
import com.yf.exam.core.api.controller.BaseController;
import com.yf.exam.core.api.dto.BaseIdReqDTO;
import com.yf.exam.core.api.dto.PagingReqDTO;
import com.yf.exam.core.exception.ServiceException;
import com.yf.exam.core.utils.excel.ExportExcel;
import com.yf.exam.core.utils.excel.ImportExcel;
import com.yf.exam.modules.trainingarchives.studentinfo.dto.export.StudentExportDTO;
import com.yf.exam.modules.trainingarchives.studentinfo.dto.req.StudentInfoReqDTO;
import com.yf.exam.modules.trainingarchives.studentinfo.dto.resp.StudentInfoRespDTO;
import com.yf.exam.modules.trainingarchives.studentinfo.service.IStudentInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 学员信息表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-12-29
 */
@Api(tags={"学员信息"})
@RestController
@RequestMapping("/org/api/student-info")
@Slf4j
public class StudentInfoController extends BaseController {

    @Resource
    private IStudentInfoService iStudentInfoService;

    /**
     * 新增学员
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增学员")
    public Result<Boolean> add(@RequestBody StudentInfoReqDTO studentInfoReqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("StudentInfoController.add.studentInfoReqDTO:{}", JSON.toJSONString(studentInfoReqDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getName()), "学员姓名不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getGender()), "性别不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getIdCard()), "身份证号不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getWorkplace()), "工作单位不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getPosition()), "岗位/工种不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getEducation()), "学历不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getPhone()), "联系电话不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getEthnicity()), "民族不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getBirthplace()), "籍贯不能为空!");
            Preconditions.checkNotNull(studentInfoReqDTO.getDob(),"出生年月不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getPoliticalStatus()), "政治面貌不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getGraduatingSchool()), "毕业院校不能为空!");
            return Result.ok(iStudentInfoService.add(studentInfoReqDTO));
        } catch (Exception e) {
            log.error("StudentInfoController.add.error:{}", e.getMessage(), e);
            return Result.faild("新增学员失败!");
        }
    }


    /**
     * 删除学员
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除学员")
    public Result<Boolean> delete(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("StudentInfoController.delete.elProjectReqDTO:{}", JSON.toJSONString(baseIdReqDTO));
            }
            Preconditions.checkNotNull(baseIdReqDTO.getId(), "学员id不能为空!");
            Boolean result = iStudentInfoService.deleteById(baseIdReqDTO.getId());
            return Result.ok(result);
        } catch (Exception e) {
            log.error("StudentInfoController.delete.error:{}", e.getMessage(), e);
            return Result.faild("删除学员失败!");
        }

    }


    /**
     * 批量删除学员信息
     */
    @PostMapping("/delete/ids")
    @ApiOperation(value = "批量删除学员")
    public Result<Boolean> deleteList(@RequestBody List<String> ids) {
        try {
            if (log.isInfoEnabled()) {
                log.info("StudentInfoController.delete.elProjectReqDTO:{}", JSON.toJSONString(ids));
            }
            Preconditions.checkNotNull(ids, "学员id不能为空!");
            Boolean result = iStudentInfoService.deleteBatch(ids);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("StudentInfoController.delete.error:{}", e.getMessage(), e);
            return Result.faild("删除学员失败!");
        }

    }

    /**
     * 更新项目
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新学员")
    public Result<Boolean> update(@RequestBody StudentInfoReqDTO studentInfoReqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("StudentInfoController.update.dto:{}", JSON.toJSONString(studentInfoReqDTO));
            }
            Preconditions.checkNotNull(studentInfoReqDTO.getId(), "学员id不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getName()), "学员姓名不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getGender()), "性别不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getIdCard()), "身份证号不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getWorkplace()), "工作单位不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getPosition()), "岗位/工种不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getEducation()), "学历不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getPhone()), "联系电话不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getEthnicity()), "民族不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getBirthplace()), "籍贯不能为空!");
            Preconditions.checkNotNull(studentInfoReqDTO.getDob(),"出生年月不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getPoliticalStatus()), "政治面貌不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(studentInfoReqDTO.getGraduatingSchool()), "毕业院校不能为空!");
            Boolean result = iStudentInfoService.updateStudent(studentInfoReqDTO);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("StudentInfoController.update.error:{}", e.getMessage(), e);
            return Result.faild("更新分类失败");
        }
    }

    /**
     * 分页查找
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @PostMapping("/paging")
    public Result<IPage<StudentInfoRespDTO>> paging(@RequestBody PagingReqDTO<StudentInfoReqDTO> reqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("StudentInfoController.paging.dto:{}", JSON.toJSONString(reqDTO));
            }
            //分页查询并转换
            IPage<StudentInfoRespDTO> page = iStudentInfoService.paging(reqDTO);
            return Result.ok(page);
        } catch (Exception e) {
            log.error("StudentInfoController.paging.error:{}", e.getMessage(), e);
            return Result.faild("查询失败");
        }
    }

    /**
     * 学员详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "获取学员详情")
    public Result<StudentInfoRespDTO> detail(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("StudentInfoController.detail.studentInfoReqDTO:{}", JSON.toJSONString(baseIdReqDTO));
            }
            Preconditions.checkArgument(!(baseIdReqDTO.getId() == null), "学员ID不能为空!");
            return Result.ok(iStudentInfoService.getDetail(baseIdReqDTO));
        } catch (Exception e) {
            log.error("StudentInfoController.detail.error:{}", e.getMessage(), e);
            return Result.faild("查询学员详情失败!");
        }
    }

    /**
     * 下载导入学员模板
     */
    @ResponseBody
    @RequestMapping(value = "/import/template", method = RequestMethod.POST)
    @ApiOperation(value = "获取学员导入模板")
    public ApiRest importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "学员导入模板.xlsx";
            List<StudentExportDTO> list = Lists.newArrayList();

            new ExportExcel("学员数据", StudentExportDTO.class, 1).setDataList(list).write(response, fileName).dispose();
            return super.success();
        } catch (Exception e) {
            return super.failure("导入模板下载失败！失败信息："+e.getMessage());
        }
    }


    /**
     * 导入学员信息Excel
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/import/questions",method = RequestMethod.POST)
    @ApiOperation(value = "导入学员信息Excel")
    public ApiRest importFileNew(@RequestParam("id") String id,@RequestParam("file") MultipartFile file) {

        try {

            if (StringUtils.isEmpty(id)) {
                throw new ServiceException(1, "培训id不能为空");
            }
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<StudentExportDTO> list = ei.getDataList(StudentExportDTO.class);

            // 校验数据
            this.checkExcel(list);

            // 导入数据条数
            iStudentInfoService.importExce(id,list);

            // 导入成功
            return super.success();

        } catch (IOException e) {

        } catch (InvalidFormatException e) {

        } catch (IllegalAccessException e) {

        } catch (InstantiationException e) {

        }

        return super.failure();
    }


    /**
     * 校验Excel
     * @param list
     * @throws Exception
     */
    private void checkExcel(List<StudentExportDTO> list) throws ServiceException {
        // 约定第三行开始导入
        int line = 3;
        StringBuffer sb = new StringBuffer();
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException(1, "您导入的数据似乎是一个空表格！");
        }
        for (StudentExportDTO item : list) {
            if (item.getName().equals("姓名")) {
                line++;
                continue;
            }
            if (item.getName() == null) {
                sb.append("第" + line + "行，学员姓名不能为空!<br>");
            }
            if (StringUtils.isBlank(item.getGender())) {
                sb.append("第" + line + "行，性别不能为空!<br>");
            }
            if (StringUtils.isBlank(item.getIdCard())) {
                sb.append("第" + line + "行，身份证号不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getWorkplace())) {
                sb.append("第" + line + "行，工作单位不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getPosition())) {
                sb.append("第" + line + "行，岗位/工种不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getEducation())) {
                sb.append("第" + line + "行，学历不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getPhone())) {
                sb.append("第" + line + "行，联系电话不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getEthnicity())) {
                sb.append("第" + line + "行，民族不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getBirthplace())) {
                sb.append("第" + line + "行，籍贯不能为空!<br>");
            }
            if (item.getDob() == null) {
                sb.append("第" + line + "行，出生年月不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getPoliticalStatus())) {
                sb.append("第" + line + "行，政治面貌不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getGraduatingSchool())) {
                sb.append("第" + line + "行，毕业院校不能为空!<br>");
            }
            line++;
        }
        // 存在错误
        if (!"".equals(sb.toString())) {
            throw new ServiceException(1, sb.toString());
        }
    }

}
